package com.yupi.springdata.springdataredis.msglistener;

import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 订阅者
 * @author li
 */
@Component
public class Subscriber implements MessageListener {
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // todo: 消息处理，日志记录，积分，邮件发送...
        // Message 封装消息管道和消息内容
        System.out.println("消息接收成功");
        // {"body":[34,104,101,108,108,111,34],"channel":[108,111,103]}
        System.out.println(JSON.toJSONString(message));
        // [108,111,103]
        System.out.println(JSON.toJSONString(pattern));

        // 管道，channel相当于key，body相当于value，可以用setKeySerializer来序列化channel，用setValueSerializer来序列化body
        byte[] channel = message.getChannel();
        System.out.println("消息管道：" + redisTemplate.getKeySerializer().deserialize(channel));
        byte[] body = message.getBody();
        System.out.println("消息内容：" + redisTemplate.getValueSerializer().deserialize(body));
    }
}
